package com.java.tutorials.jdk7.fileattribute;

import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.GroupPrincipal;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.UserPrincipal;
import java.nio.file.attribute.UserPrincipalLookupService;
/**
 * Created by xuzhike on 2016/1/24.
 * http://www.java2s.com/Code/Java/JDK-7/SetgroupPrincipal.htm
 */
public class SetgroupPrincipal {
    public static void main(String[] args) throws Exception {
        Path path = Paths.get("home/docs/users.txt");
        setGroupPrincipal(path, "A", "B");
    }
    private static void setGroupPrincipal(Path path, String userName,
                                          String groupName) throws Exception {
        System.out.println("Setting owner for " + path.getFileName());
        PosixFileAttributeView view = Files.getFileAttributeView(path,
                PosixFileAttributeView.class);

        PosixFileAttributes attributes = view.readAttributes();
        System.out.println("Old Group: " + attributes.group().getName());
        System.out.println("Old Owner: " + attributes.owner().getName());

        UserPrincipalLookupService lookupService = FileSystems.getDefault()
                .getUserPrincipalLookupService();
        UserPrincipal userPrincipal = lookupService.lookupPrincipalByName(userName);
        GroupPrincipal groupPrincipal = lookupService
                .lookupPrincipalByGroupName(groupName);
        view.setGroup(groupPrincipal);
        view.setOwner(userPrincipal);

        attributes = view.readAttributes();
        System.out.println("New Group: " + attributes.group().getName());
        System.out.println("New Owner: " + attributes.owner().getName());
    }
}
